<template>
  <div class="edit-container">
    <el-steps :active="fbOptions.curStep" align-center>
      <el-step
        style="cursor: pointer"
        v-for="(n, i) in fbOptions.steps"
        :key="n.key"
        :title="n.title"
        @click.stop="changeStep(i)"
      ></el-step>
    </el-steps>
    <div class="body">
      <!-- <transition name="fade" mode="out-in" appear> -->
      <keep-alive>
        <template v-for="item in fbOptions.steps">
          <component
            :fbOptions="fbOptions"
            :formData="fbOptions.formData"
            v-if="fbOptions.steps[fbOptions.curStep].key === item.key"
            :key="item.key"
            :is="`step-${item.name}`"
            ref="child"
          />
        </template>
      </keep-alive>
      <!-- </transition> -->
    </div>
    <div class="footer" ref="footerRef">
      <el-button @click="onClose">关闭</el-button>
      <el-button
        v-show="fbOptions.curStep === 0 && fbOptions.operationType === 'add'"
        @click="onBack"
      >返回
      </el-button
      >
      <el-button v-show="fbOptions.curStep !== 0" @click="onPre">上一步</el-button>
      <el-button v-show="handleSaveShow" type="primary" @click="onNext('save')"
      >暂存
      </el-button
      >
      <el-button
        v-if="fbOptions.curStep !== fbOptions.steps.length - 1"
        type="primary"
        @click="onNext('next')"
      >下一步
      </el-button
      >
      <!-- <el-button v-show="fbOptions.curStep === steps.length - 1" type="primary" @click="onSubmit">提交审核</el-button> -->
    </div>
  </div>

</template>

<script>

import {saveNLBP, savePzxxProtocol, upgradePzxxProtocol} from "@slc/api/slc/inventory";
import StepPzxx from './step-pzxx.vue'
import StepQqt from './step-qqt.vue'
import StepSrcs from './step-srcs.vue'
import StepSccs from './step-sccs.vue'
import StepCsfb from './step-csfb.vue'
import StepNlbp from '../nlbp/index.vue'

export default {
  name: "index",
  data(){
    return{
    }
  },
  components: {
      StepPzxx,
      StepQqt,
      StepSrcs,
      StepSccs,
      StepCsfb,
      StepNlbp
    // StepPzxx: () => import("./step-pzxx.vue"),
    // StepQqt: () => import("./step-qqt.vue"),
    // StepSrcs: () => import("./step-srcs.vue"),
    // StepNlbp: () => import("../nlbp/index.vue"),
    // StepSccs: () => import("./step-sccs.vue"),
    // StepCsfb: () => import("./step-csfb.vue"),
  },
    props: {
        fbOptions: {
            type: Object,
            // required: false,
            default: () => {
            },
        }
    },
  computed: {
    handleSaveShow() {
      const pzxxIndex = this.fbOptions.steps.findIndex((n) => n.key === "PZXX");
      return this.fbOptions.curStep >= pzxxIndex;
    },
    pzxxIndex() {
      return this.fbOptions.steps.findIndex((n) => n.key === "PZXX");
    },
  },
  methods: {
    changeStep(i) {
      if (this.fbOptions.formData.serviceVerId && i < this.pzxxIndex) {
        this.$message.error("数据已保存，不可以修改！");
        return;
      }
    },
    onPre() {
      // 如果保存过配置，返回了serviceVerId,则不能回到配置之前的步骤
      if (this.fbOptions.formData.serviceVerId && this.fbOptions.curStep <= this.pzxxIndex) {
        this.$message.error("数据已保存，不可以修改！");
        return;
      }
      this.fbOptions.curStep -= 1;
    },
    async onNext(key) {
      if (key === "save" && this.fbOptions.steps[this.fbOptions.curStep].key === "CSFB") {
        this.onClose();
        this.$emit('refresh');
        return;
      }

      switch (this.fbOptions.steps[this.fbOptions.curStep].key) {
        case "PZXX":
          if (!this.fbOptions.formData.serviceName) {
            this.$message.error("请输入能力名称！");
            return;
          }
          if (!this.fbOptions.formData.servicePath) {
            this.$message.error('请输入能力别名！')
            return
          }
          if (this.fbOptions.formData.cateIds.length === 0) {
            this.$message.error("请选择所属分类！");
            return;
          }
          if (!this.fbOptions.formData.serviceDesc) {
            this.$message.error("请输入能力描述！");
            return;
          }
          this.submit();
          break;
        case "QQT":
          this.fbOptions.curStep++;
          // this.$emit('update:fbOptions', this.fbOptions);

          break;
        case "SRCS":
        case "SCCS":
          this.fbOptions.curStep++;
          break;
        case "NLBP":
          const params = {
            serviceVerId: this.fbOptions.formData.serviceVerId,
            contentText: JSON.stringify(this.handleNlbpSaveData()),
          };
          const res = await saveNLBP(params);
          if (res.code === "200") {
            this.fbOptions.curStep++;
          }
          break;

      }
      if (key === "save") {
        this.onClose();
      }


    },
    async submit() {
      let fn
      if (this.fbOptions.operationType === 'upgrade' ) {
        fn = upgradePzxxProtocol
      } else {
        fn = savePzxxProtocol
      }
      const cateId = this.fbOptions.formData.cateIds.at(-1);
      const limitCtrlStatus = this.fbOptions.formData.limitCtrlStatus ? '0' : '2';
      const res = await fn({...this.fbOptions.formData, serverReleaseType: '2', cateId, limitCtrlStatus});
      if (res.code === '200') {
         Object.keys(res.data).map(e=>{
           if(!res.data[e]){
              delete res.data[e];
           }
         })
        let formData = {...this.fbOptions.formData, ...res.data};
        this.fbOptions.curStep++;
        this.fbOptions.flow.serviceDomain = { root: true };
        this.$emit('updateFbOptions', {...this.fbOptions, formData: formData});

          // this.fbOptions =  {...this.fbOptions, formData: formData}

      }
    },
    onBack() {
      this.$emit('updateFbOptions', {...this.fbOptions, isVisible: false});

    },
    onClose() {
      if(this.fbOptions.versionTo){
        this.$emit('updateFbOptions', {...this.fbOptions, operationType: 'version'});
      }else{
        this.$emit('updateFbOptions', {...this.fbOptions, isVisible: false});
      }
    },
    handleNlbpSaveData() {
      this.fbOptions.flow.graph.getCells().forEach(cell => {
        cell.removeTools()
      })
      let graphData = this.fbOptions.flow.graph.toJSON();
      graphData.cells = graphData.cells.map((n) => {
        let type;
        if (n.shape === "edge") {
          type = "line";
        } else {
          type = n.data ? n.data.type : "";
        }
        let obj = {};
        if (type === 'from-rest') {
          obj = {
            http_method:  this.fbOptions.flow.serviceDomain.httpRequestMethod
          }
        }
        if (this.fbOptions.flow.moreNodeInfo[n.id]) {
          if (type === "controller-multicast") {
            obj = {
              parallel_processing: this.fbOptions.flow.moreNodeInfo[n.id].parallel_processing, // 【必传，boolean】并行分发
              stop_on_exception: this.fbOptions.flow.moreNodeInfo[n.id].stop_on_exception, // 【必传，boolean】异常停止，仅串行时生效
              timeout: this.fbOptions.flow.moreNodeInfo[n.id].timeout, // 【必传，int】 超时(毫秒)
            }
          } else if (type === "processor-JsonToSoapXml") {
            const soapNode = this.fbOptions.flow.moreNodeInfo[this.fbOptions.flow.moreNodeInfo[n.id].soapId] || {}
            obj = {
              soap_wsdl_url: soapNode.apiUrl, //【必传，string】WSDL路径
              soap_operation: soapNode.httpRequestMethod, //【必传，string】WSDL中请求方法,
              xml_node_xpath: this.fbOptions.flow.moreNodeInfo[n.id].paramInSerializeName, //【可空，string】入参名称
              param_serialize: this.fbOptions.flow.moreNodeInfo[n.id].isParamSerialize, //【必传，boolean】参数是否序列化
              soap_direction: this.fbOptions.flow.moreNodeInfo[n.id].soap_direction
            };
          } else if (type === "to-soap") {
            obj = {
              endpoint_url: this.fbOptions.flow.moreNodeInfo[n.id].apiUrl, //【必传，string】API接口服务地址
              soap_wsdl_url: this.fbOptions.flow.moreNodeInfo[n.id].apiUrl, //【必传，string】API接口服务WSDL地址
              target_auth_type: this.fbOptions.flow.moreNodeInfo[n.id].targetAuthType, //【必传，string】API接口认证方式
              app_id: this.fbOptions.flow.moreNodeInfo[n.id].appId, //【必传，string】API接口所属应用ID
            };
          } else if (type === "processor-SoapXmlToJson") {
            const soapNode = this.fbOptions.flow.moreNodeInfo[this.fbOptions.flow.moreNodeInfo[n.id].soapId] || {}
            obj = {
              soap_operation: soapNode.apiUrl, //【必传，string】请求方法
              xml_node_xpath: this.fbOptions.flow.moreNodeInfo[n.id].paramOutSerializeName, //【必传，string】出参名称
              body_with_attr: this.fbOptions.flow.moreNodeInfo[n.id].outparamWithAttr, //【必传，string】参数是否带属性
              soap_direction: this.fbOptions.flow.moreNodeInfo[n.id].soap_direction
            };
          } else if (type === "to-rest") {
            obj = {
              endpoint_url: this.fbOptions.flow.moreNodeInfo[n.id].mockUrl, //【必传，string】API接口服务地址
              target_auth_type: this.fbOptions.flow.moreNodeInfo[n.id].targetAuthType, //【必传，string】API接口认证方式
              app_id: this.fbOptions.flow.moreNodeInfo[n.id].appId, //【必传，string】API接口所属应用ID
            };
          } else if (type === "to-jms") {
            obj = {
              queue_name: this.fbOptions.flow.moreNodeInfo[n.id].queue_name, //【必传，string】队列名称
            };
          } else if (type === "to-dataset") {
            obj = {
              sql: this.fbOptions.flow.moreNodeInfo[n.id].selectSql, //【必传，string】查询SQL语句
              datasource: this.fbOptions.flow.moreNodeInfo[n.id].datasourceId, ////【必传，string】队列名称数据源名称
            };
          } else if (type === "processor-RawToFormData") {
            const nextNode = this.fbOptions.flow.graph.getNeighbors(this.fbOptions.flow.graph.getCellById(n.id))[0] || {}
            let http_method = ''
            if (nextNode.id) {
              http_method = this.fbOptions.flow.moreNodeInfo[nextNode.id].httpRequestMethod
            }
            obj = {
              http_method //【必传，string】请求方式
            };
          } else if (type === "processor-ParamBuilderJson") {
            const nextNode = this.fbOptions.flow.moreNodeInfo[this.fbOptions.flow.moreNodeInfo[n.id].nextId] || {}
            obj = {
              paramOut: nextNode.inParamList //【必传，string】请求方式
            };
          } else if (type === "line") {
            obj = {
              isDefault: this.fbOptions.flow.moreNodeInfo[n.id].isDefault, //【必填，boolean】是否默认分支
              rule: this.fbOptions.flow.moreNodeInfo[n.id].isDefault ? '<otherwise/>' : this.fbOptions.flow.moreNodeInfo[n.id].rule  //【可选，string】条件表达式
            }
          }
        }
        n.form = {
          type,
          data: {
            ...obj,
          },
        };
        return n;
      });
      return {
        properties: {
          serviceDomain: this.fbOptions.flow.serviceDomain,
          moreNodeInfo: this.fbOptions.flow.moreNodeInfo,
        },
        ...graphData,
      };
    },
  }

}
</script>

<style lang="scss" scoped>
.el-button--primary:focus {
  background: #1890ff;
  border-color: #1890ff;
}

.edit-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .body {
    margin: 16px 0;
    flex: 1;
  }

  .footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
